package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.*;
import com.itheima.service.UserService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //根据用户名查询用户信息
    @Override
    public User findByUsername(String username) {
        //查找用户信息
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }

        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                //根据角色id查询到权限信息
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissions(permissions);//让角色关联权限
                }
            }
            user.setRoles(roles);//让用户关联角色
        }
        return user;
    }

    //修改密码
    @Override
    public Boolean editPwd(String username, Map map) {
        String oldpwd = (String) map.get("oldpassword");
        String newpwd = (String) map.get("newpassword");
        //1.根据用户名查找用户
        User user = userDao.findByUsername(username);
        if (passwordEncoder.matches(oldpwd, user.getPassword())) {
            userDao.editPwd(passwordEncoder.encode(newpwd), username);
            return true;
        } else {
            return false;
        }

    }

    //带分页查找用户信息
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //PageHelper pageHelper = new PageHelper();
        PageHelper.startPage(currentPage, pageSize);

        Page<User> page = userDao.findByCondition(queryString);

        Long total = page.getTotal();
        List rows = page.getResult();


        return new PageResult(total, rows);
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        //添加新用户
        String pwd = passwordEncoder.encode(user.getPassword());

        user.setPassword(pwd);

        userDao.add(user);

        Integer userId = user.getId();

        setUserAndRole(userId, roleIds);


    }

    //通过用户id查找关联的角色id
    @Override
    public List<Integer> findRoleIdsByUserId(Integer userId) {
        return userDao.findRoleIdsByUserId(userId);
    }

    //根据用户id查询用户信息
    @Override
    public User findById(Integer userId) {
        return userDao.findById(userId);
    }

    //更新用户信息
    @Override
    public void edit(User user, Integer[] roleIds) {

        Integer id = user.getId();

        User user1 = userDao.findById(id);

        if(user1.getUsername().equals("admin") && !user.getUsername().equals("admin")){
            throw new RuntimeException("该用户为超级用户，无法修改用户名");
        }

        //给密码加密
        String pwd = passwordEncoder.encode(user.getPassword());
        user.setPassword(pwd);
        //保存编辑信息
        userDao.edit(user);
        //删除旧关系
        userDao.deleteAssoication(user.getId());
        //建立新关系
        setUserAndRole(user.getId(), roleIds);
    }

    //根据id删除用户
    @Override
    public void deleteById(Integer id) {

        //检查删除id是否和角色表有关联
        List<Integer> list =  userDao.findRoleIdsByUserId(id);

        if (!list.isEmpty()) {
            throw new RuntimeException("用户和"+list.size()+"个角色相关联");
        }else {
            userDao.deleteById(id);
        }
    }

    //建立用户和角色关联
    public void setUserAndRole(Integer userId, Integer[] roleIds) {

        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

    @Override
    public List<User> findAllUser() {
        return userDao.findUserByHealthManager();
    }

    @Override
    public List<Menu> findAllMenu(String username) {

        List<Menu> list = userDao.findAllMenu(username);

        List<Menu> menuList = new ArrayList<>();


        for (Menu menu : list) {
            if (menu.getParentMenuId() == null ) {
                menuList.add(menu);
            }
        }

        if (!menuList.isEmpty()) {
            for (Menu menu1 : menuList) {
                for (Menu menu : list) {
                    if (  menu.getParentMenuId()!=null && menu.getParentMenuId() == menu1.getId()) {
                        menu1.getChildren().add(menu);
                    }
                }
            }
        }
        return menuList;
    }

    @Override
    public User findByTelephone(String telephone) {
        //查找用户信息
        User user = userDao.findByTelephone(telephone);
        if (user == null) {
            return null;
        }else {

            Integer userId = user.getId();
            //根据用户ID查询对应的角色
            Set<Role> roles = roleDao.findByUserId(userId);
            if (roles != null && roles.size() > 0) {
                for (Role role : roles) {
                    Integer roleId = role.getId();
                    //根据角色id查询到权限信息
                    Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                    if (permissions != null && permissions.size() > 0) {
                        role.setPermissions(permissions);//让角色关联权限
                    }
                }
                user.setRoles(roles);//让用户关联角色
            }
            return user;
        }

        //return userDao.findByTelephone(telephone);
    }

    @Override
    public void editPwdByTelandNewPwd(String telephone, String password) {
        User user = userDao.findByTelephone(telephone);
        userDao.editPwd(passwordEncoder.encode(password), user.getUsername());

        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                //根据角色id查询到权限信息
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissions(permissions);//让角色关联权限
                }
            }
            user.setRoles(roles);//让用户关联角色
        }
        //return userDao.findByTelephone(telephone);
    }

    @Override
    public void changeStatus(Map<String, Object> map, String username) {
        User user = userDao.findByUsername(username);

        Integer id = (Integer) map.get("id");
        User user1 = userDao.findById(id);
        String station = (String) map.get("station");

        if (user.getId() == id || user1.getUsername().equals("admin")) {
            throw new RuntimeException("当前用户为超级管理员，无法修改当前用户状态");
        }
        userDao.changeStatus(id,station);

    }
}
